package luj.tool.jnproxyan.proxy.stats.connect;

import luj.data.api.Data;
import luj.data.api.field.type.JMap;
import luj.data.api.use.UseGroup;
import luj.tool.jnproxyan.proxy.database.DatabaseState;
import luj.tool.jnproxyan.proxy.util.data.DataNewCreator;
import luj.tool.jnproxyan.proxy.util.data.session.DataUsingStarter;
import luj.tool.jnproxyan.proxy.util.data.wrap.DataResultWrapper;
import luj.tool.jnproxyan.proxy.util.data.wrap.ResultByIdLWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class StatsItemGetter {

  public StatsItemGetter inject(ConnectStats stats, String host, DataUsingStarter.Session session) {
    return inject(stats, host, session.db(), session.loaded(), session.using());
  }

  public StatsItemGetter inject(ConnectStats stats, String host, DatabaseState dbState, Map<String, Data> loadCache, UseGroup using) {
    StatsItemGetter result = new StatsItemGetter();
    result._stats = stats;
    result._host = host;
    result._dbState = dbState;
    result._loadCache = loadCache;
    result._using = using;

    result._byIdLoader = _byIdLoader;
    result._dataMaker = _dataMaker;
    result._dataWrapper = _dataWrapper;

    return result;
  }

  public ConnectStats.Item getOrInit() {
    JMap<String, Long> statMap = _stats.statsMap();
    Long oldItem = statMap.get(_host);

    Class<ConnectStats.Item> itemType = ConnectStats.Item.class;
    if (oldItem != null) {
      return _byIdLoader.load(oldItem, _dbState, _loadCache, _using).andWrap(itemType);
    }

    Data data = _dataMaker.inject(itemType, _dbState).create();
    ConnectStats.Item newItem = _dataWrapper.inject(data, _loadCache, _using, true).wrap(itemType);
    newItem.host().set(_host);

    statMap.put(_host, (Long) data.getId());
    return newItem;
  }

  ConnectStats _stats;
  String _host;

  DatabaseState _dbState;
  Map<String, Data> _loadCache;
  UseGroup _using;

  @Autowired
  ResultByIdLWrapper _byIdLoader;

  @Autowired
  DataNewCreator _dataMaker;

  @Autowired
  DataResultWrapper _dataWrapper;
}
